<template>
  <div class="order-detail-container">
    <!-- 页面标题和返回按钮 -->
    <div class="page-header">
      <el-button type="default" icon="ArrowLeft" @click="handleBack">返回列表</el-button>
      <h1>订单详情</h1>
    </div>

    <!-- 订单基本信息卡片 -->
    <el-card class="base-info-card">
      <div class="card-header">
        <h2>订单基本信息</h2>
        <div class="order-status">
          <el-tag :type="getStatusTagType(orderInfo.status)">{{ getStatusText(orderInfo.status) }}</el-tag>
        </div>
      </div>

      <div class="info-grid">
        <div class="info-item">
          <span class="label">订单编号：</span>
          <span class="value">{{ orderInfo.orderNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">下单时间：</span>
          <span class="value">{{ orderInfo.createTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">供应商名称：</span>
          <span class="value">{{ orderInfo.supplierName }}</span>
        </div>
        <div class="info-item">
          <span class="label">供应商编码：</span>
          <span class="value">{{ orderInfo.supplierId }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系人：</span>
          <span class="value">{{ orderInfo.contactPerson }}</span>
        </div>
        <div class="info-item">
          <span class="label">联系电话：</span>
          <span class="value">{{ orderInfo.contactPhone }}</span>
        </div>
        <div class="info-item">
          <span class="label">收货地址：</span>
          <span class="value">{{ orderInfo.provinceName }}{{ orderInfo.cityName }}{{ orderInfo.address }}</span>
        </div>
        <div class="info-item">
          <span class="label">收货单位：</span>
          <span class="value">{{ orderInfo.receiveUnit }}</span>
        </div>
      </div>
    </el-card>

    <!-- 商品列表卡片 -->
    <el-card class="product-list-card">
      <div class="card-header">
        <h2>商品清单</h2>
        <div class="product-count">共 {{ orderInfo.productCount }} 件商品</div>
      </div>

      <el-table
        :data="orderInfo.products"
        border
        stripe
        size="small"
      >
        <el-table-column prop="productName" label="商品名称" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="productCode" label="商品编码" min-width="140"></el-table-column>
        <el-table-column prop="specification" label="规格型号" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column prop="unit" label="单位" min-width="80"></el-table-column>
        <el-table-column prop="quantity" label="数量" min-width="80" align="right"></el-table-column>
        <el-table-column prop="price" label="单价" min-width="100" align="right">
          <template #default="scope">{{ scope.row.price | formatCurrency }}</template>
        </el-table-column>
        <el-table-column prop="amount" label="金额" min-width="100" align="right">
          <template #default="scope">{{ scope.row.amount | formatCurrency }}</template>
        </el-table-column>
        <el-table-column prop="taxRate" label="税率(%)" min-width="90" align="right"></el-table-column>
        <el-table-column prop="taxAmount" label="税额" min-width="100" align="right">
          <template #default="scope">{{ scope.row.taxAmount | formatCurrency }}</template>
        </el-table-column>
      </el-table>

      <!-- 金额汇总 -->
      <div class="amount-summary">
        <div class="summary-item">
          <span class="label">商品金额：</span>
          <span class="value">{{ orderInfo.subTotal | formatCurrency }}</span>
        </div>
        <div class="summary-item">
          <span class="label">税额：</span>
          <span class="value">{{ orderInfo.taxTotal | formatCurrency }}</span>
        </div>
        <div class="summary-item">
          <span class="label">运费：</span>
          <span class="value">{{ orderInfo.freight | formatCurrency }}</span>
        </div>
        <div class="summary-item total">
          <span class="label">订单总金额：</span>
          <span class="value">{{ orderInfo.totalAmount | formatCurrency }}</span>
        </div>
      </div>
    </el-card>

    <!-- 物流信息卡片 -->
    <el-card class="logistics-card" v-if="orderInfo.logisticsInfo">
      <div class="card-header">
        <h2>物流信息</h2>
      </div>

      <div class="logistics-info">
        <div class="info-item">
          <span class="label">物流公司：</span>
          <span class="value">{{ orderInfo.logisticsInfo.logisticsCompany }}</span>
        </div>
        <div class="info-item">
          <span class="label">物流单号：</span>
          <span class="value">{{ orderInfo.logisticsInfo.logisticsNo }}</span>
        </div>
        <div class="info-item">
          <span class="label">发货时间：</span>
          <span class="value">{{ orderInfo.logisticsInfo.shipTime }}</span>
        </div>
        <div class="info-item">
          <span class="label">预计到达：</span>
          <span class="value">{{ orderInfo.logisticsInfo.estimateArriveTime }}</span>
        </div>
      </div>
    </el-card>

    <!-- 订单操作历史 -->
    <el-card class="operation-history-card">
      <div class="card-header">
        <h2>订单操作历史</h2>
      </div>

      <el-timeline>
        <el-timeline-item
          v-for="(item, index) in orderInfo.operationHistory"
          :key="index"
          :timestamp="item.operateTime"
          :color="index === 0 ? 'green' : 'blue'"
        >
          <div class="timeline-content">
            <div class="operate-desc">{{ item.operateDesc }}</div>
            <div class="operate-user">操作人：{{ item.operateUser }}</div>
            <div class="operate-remark" v-if="item.remark">备注：{{ item.remark }}</div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>

    <!-- 操作按钮区 -->
    <div class="action-buttons" v-if="showActionButtons">
      <el-button type="primary" @click="handleUpdateStatus(2)" v-if="orderInfo.status == 1">
        <el-icon><Truck /></el-icon> 标记发货
      </el-button>
      <el-button type="success" @click="handleUpdateStatus(4)" v-if="orderInfo.status == 3">
        <el-icon><Check /></el-icon> 标记完成
      </el-button>
      <el-button type="danger" @click="handleUpdateStatus(5)" v-if="[0,1].includes(orderInfo.status)">
        <el-icon><Close /></el-icon> 取消订单
      </el-button>
      <el-button type="warning" @click="handleUpdateStatus(6)" v-if="![5,6].includes(orderInfo.status)">
        <el-icon><Warning /></el-icon> 标记异常
      </el-button>
      <el-button type="default" @click="handlePrint">
        <el-icon><Printer /></el-icon> 打印订单
      </el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ArrowLeft, Truck, Check, Close, Warning, Printer } from '@element-plus/icons-vue';
import { ElMessage, ElMessageBox } from 'element-plus';

// 定义订单状态类型
type OrderStatus = 0 | 1 | 2 | 3 | 4 | 5 | 6;

// 定义商品接口
interface ProductItem {
  id: string;
  productName: string;
  productCode: string;
  specification: string;
  unit: string;
  quantity: number;
  price: number;
  amount: number;
  taxRate: number;
  taxAmount: number;
}

// 定义物流信息接口
interface LogisticsInfo {
  logisticsCompany: string;
  logisticsNo: string;
  shipTime: string;
  estimateArriveTime: string;
}

// 定义操作历史接口
interface OperationHistory {
  operateTime: string;
  operateDesc: string;
  operateUser: string;
  remark?: string;
}

// 定义订单详情接口
interface OrderDetail {
  id: string;
  orderNo: string;
  status: OrderStatus;
  createTime: string;
  supplierName: string;
  supplierId: string;
  contactPerson: string;
  contactPhone: string;
  provinceName: string;
  cityName: string;
  address: string;
  receiveUnit: string;
  productCount: number;
  products: ProductItem[];
  subTotal: number;
  taxTotal: number;
  freight: number;
  totalAmount: number;
  logisticsInfo?: LogisticsInfo;
  operationHistory: OperationHistory[];
}

// 状态管理
const loading = ref(true);
const orderInfo = ref<OrderDetail>({} as OrderDetail);
const route = useRoute();
const router = useRouter();
const orderId = route.params.id as string;

// 显示操作按钮（根据用户权限和订单状态）
const showActionButtons = computed(() => {
  // 实际项目中应根据用户权限动态控制
  return true;
});

// 格式化金额过滤器
const formatCurrency = (value: number) => {
  return new Intl.NumberFormat('zh-CN', { style: 'currency', currency: 'CNY' }).format(value);
};

// 获取订单状态文本
const getStatusText = (status: OrderStatus): string => {
  const statusMap = {
    0: '待确认',
    1: '已确认',
    2: '已发货',
    3: '已收货',
    4: '已完成',
    5: '已取消',
    6: '异常'
  };
  return statusMap[status] || '未知';
};

// 获取订单状态标签类型
const getStatusTagType = (status: OrderStatus): string => {
  const typeMap = {
    0: 'info',
    1: 'primary',
    2: 'success',
    3: 'processing',
    4: 'success',
    5: 'danger',
    6: 'warning'
  };
  return typeMap[status] || 'default';
};

// 返回订单列表
const handleBack = () => {
  router.push({ name: 'OrderList' });
};

// 更新订单状态
const handleUpdateStatus = async (status: OrderStatus) => {
  const statusText = getStatusText(status);
  const confirmMessage = status === 5 ? '确定要取消订单吗？取消后将无法恢复。' : `确定要将订单状态更新为${statusText}吗？`;
  const inputPlaceholder = status === 6 ? '请输入异常原因' : (status === 5 ? '请输入取消原因' : '请输入备注信息');
  const needInput = [5, 6].includes(status);

  try {
    let remark = '';
    if (needInput) {
      // 需要输入备注信息
      const inputResult = await ElMessageBox.prompt(confirmMessage, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPlaceholder,
        inputValidator: (value) => {
          if (!value.trim()) {
            return inputPlaceholder;
          }
          return true;
        }
      });
      remark = inputResult.value;
    } else {
      // 不需要输入备注，直接确认
      await ElMessageBox.confirm(confirmMessage, '确认操作', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      });
    }

    // 模拟API请求
    loading.value = true;
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 更新本地状态
    orderInfo.value.status = status;
    // 添加操作历史
    orderInfo.value.operationHistory.unshift({
      operateTime: new Date().toISOString().slice(0, 19).replace('T', ' '),
      operateDesc: `订单状态更新为${statusText}`,
      operateUser: '当前用户',
      remark
    });

    ElMessage.success(`订单已${statusText}`);
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('更新订单状态失败');
      console.error('更新订单状态失败:', error);
    }
  } finally {
    loading.value = false;
  }
};

// 打印订单
const handlePrint = () => {
  // TODO: 实现打印功能
  ElMessage.info('打印功能开发中...');
};

// 获取订单详情数据
const fetchOrderDetail = async () => {
  loading.value = true;
  try {
    // 模拟API请求
    await new Promise(resolve => setTimeout(resolve, 1000));

    // 生成模拟数据
    const now = new Date();
    const yesterday = new Date(now.getTime() - 24 * 60 * 60 * 1000);
    const twoDaysAgo = new Date(now.getTime() - 2 * 24 * 60 * 60 * 1000);

    orderInfo.value = {
      id: orderId,
      orderNo: `ZCY${Date.now().toString().slice(-10)}`,
      status: Math.floor(Math.random() * 4) as OrderStatus,
      createTime: twoDaysAgo.toISOString().slice(0, 19).replace('T', ' '),
      supplierName: `供应商${Math.floor(Math.random() * 1000) + 1}`,
      supplierId: `SP${Math.floor(Math.random() * 10000).toString().padStart(6, '0')}`,
      contactPerson: `联系人${Math.floor(Math.random() * 100)}`,
      contactPhone: `13${Math.floor(Math.random() * 100000000).toString().padStart(8, '0')}`,
      provinceName: ['浙江省', '北京市', '上海市'][Math.floor(Math.random() * 3)],
      cityName: ['杭州市', '北京市', '上海市'][Math.floor(Math.random() * 3)],
      address: `测试地址${Math.floor(Math.random() * 100)}号`,
      receiveUnit: `收货单位${Math.floor(Math.random() * 100)}`,
      productCount: 3,
      subTotal: 25600,
      taxTotal: 3072,
      freight: 100,
      totalAmount: 28772,
      products: [
        {
          id: '1',
          productName: '高性能笔记本电脑',
          productCode: 'NB-2023-001',
          specification: 'i7/16G/1TB/14英寸',
          unit: '台',
          quantity: 2,
          price: 8999,
          amount: 17998,
          taxRate: 13,
          taxAmount: 2072
        },
        {
          id: '2',
          productName: '无线鼠标',
          productCode: 'MS-2023-002',
          specification: '蓝牙/黑色',
          unit: '个',
          quantity: 2,
          price: 129,
          amount: 258,
          taxRate: 13,
          taxAmount: 28
        },
        {
          id: '3',
          productName: '机械键盘',
          productCode: 'KB-2023-003',
          specification: '青轴/背光/有线',
          unit: '个',
          quantity: 1,
          price: 399,
          amount: 399,
          taxRate: 13,
          taxAmount: 44
        }
      ],
      logisticsInfo: Math.random() > 0.3 ? {
        logisticsCompany: ['顺丰速运', '圆通快递', '中通快递'][Math.floor(Math.random() * 3)],
        logisticsNo: `SF${Math.floor(Math.random() * 10000000000).toString().padStart(10, '0')}`,
        shipTime: yesterday.toISOString().slice(0, 19).replace('T', ' '),
        estimateArriveTime: new Date(now.getTime() + 2 * 24 * 60 * 60 * 1000).toISOString().slice(0, 10)
      } : undefined,
      operationHistory: [
        {
          operateTime: twoDaysAgo.toISOString().slice(0, 19).replace('T', ' '),
          operateDesc: '创建订单',
          operateUser: '系统自动创建'
        },
        {
          operateTime: new Date(twoDaysAgo.getTime() + 3600 * 1000).toISOString().slice(0, 19).replace('T', ' '),
          operateDesc: '订单状态更新为已确认',
          operateUser: '张三',
          remark: '确认订单无误'
        }
      ]
    };
  } catch (error) {
    ElMessage.error('获取订单详情失败');
    console.error('获取订单详情失败:', error);
  } finally {
    loading.value = false;
  }
};

// 页面加载时获取数据
onMounted(() => {
  fetchOrderDetail();
});
</script>

<style scoped lang="scss">
.order-detail-container {
  padding: 0 20px;
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 20px;
  gap: 15px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
  padding-bottom: 10px;
  border-bottom: 1px solid #eee;
}

.base-info-card,
.product-list-card,
.logistics-card,
.operation-history-card {
  margin-bottom: 20px;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px 20px;
}

.info-item {
  display: flex;
}

.label {
  color: #606266;
  width: 100px;
  flex-shrink: 0;
}

.value {
  flex-grow: 1;
  word-break: break-all;
}

.product-count {
  color: #606266;
  font-size: 14px;
}

.amount-summary {
  margin-top: 15px;
  padding-top: 15px;
  border-top: 1px solid #eee;
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-end;
  gap: 20px 40px;
}

.summary-item {
  display: flex;
  align-items: center;
}

.summary-item.total {
  color: #f56c6c;
  font-weight: bold;
  font-size: 16px;
}

.logistics-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 15px;
}

.timeline-content {
  padding: 5px 0;
}

.operate-desc {
  font-weight: 500;
  margin-bottom: 3px;
}

.operate-user,
.operate-remark {
  font-size: 12px;
  color: #606266;
  margin-bottom: 2px;
}

.action-buttons {
  display: flex;
  justify-content: center;
  gap: 15px;
  margin-top: 20px;
  margin-bottom: 30px;
}

/* 适配小屏幕 */
@media (max-width: 768px) {
  .order-detail-container {
    padding: 0 10px;
  }

  .info-grid,
  .logistics-info {
    grid-template-columns: 1fr;
  }

  .action-buttons {
    flex-wrap: wrap;
  }
}
</style>